﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;


public class ColliderTool : Editor {
    //建筑太复杂，这里只是粗略添加一个，好测试功能。这里是找到子物体里最大的网格渲染器添加boxcollider，最好用于静态物体的添加
    [MenuItem("Tools/Collider/自动添加碰撞器(给子物体添加，如建筑)", false, 100)]
	/// <summary>
	/// 自动添加碰撞器(给子物体添加，如建筑)
	/// </summary>
    public static void BindBoxColliderForWhole() {//添加box碰撞器
        Debug.ClearDeveloperConsole();
        Object[] objs = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
        List<string> prefabPath = new List<string>();
        foreach (Object o in objs)
        {
        //Debug.Log(Application.dataPath.Replace("Assets", "")+AssetDatabase.GetAssetPath(o));
        //E:/ UnityProject / BorderExpansion / borderExpansionProj / Assets / Area730 / Stylized city / city.prefab
            FileInfo fi = new FileInfo(Application.dataPath.Replace("Assets","")+ AssetDatabase.GetAssetPath(o));
            //Debug.Log(fi.Name.Substring(fi.Name.LastIndexOf('.') + 1));
            if (fi.Name.Substring(fi.Name.LastIndexOf('.') + 1) == "prefab")
            {
                //prefabPath.Add(AssetDatabase.GetAssetPath(o));
                //Debug.Log(AssetDatabase.GetAssetPath(o));
                //Assets / Area730 / Stylized city / city.prefab
                //根对象
                GameObject srcClip = AssetDatabase.LoadAssetAtPath(AssetDatabase.GetAssetPath(o), typeof(GameObject)) as GameObject;
                for(int i = 0; i < srcClip.transform.childCount; i++)
                {
                    GameObject sub = srcClip.transform.GetChild(i).gameObject;
                    Vector3 maxsize = Vector3.zero;
                    GameObject toAddColliderObj = null;
                    for (int j = 0; j < sub.transform.childCount; j++) {
                        GameObject temp = sub.transform.GetChild(j).gameObject;
                        if (temp.GetComponent<BoxCollider>() != null)
                        {
                            continue;
                        }
                        Renderer smr = temp.GetComponentInChildren<Renderer>();
                        if (smr == null)
                        {
                            Debug.LogError(temp.ToString() + "没有MeshRenderer");
                            continue;
                        }
                        if (smr.bounds.extents.magnitude> maxsize.magnitude) {
                            maxsize = smr.bounds.extents;
                            toAddColliderObj = temp;
                        }
                    }
                    if (toAddColliderObj != null)
                    {
                        toAddColliderObj.gameObject.AddComponent<BoxCollider>();
                    }
                    else {//没有child，如果自己本身有render则直接在自己身上加
                        if (sub.GetComponent<Renderer>() != null) {
                            sub.gameObject.AddComponent<BoxCollider>();
                        }       
                    }
                }
            }
        }
    }

    //建筑太复杂，这里只是粗略添加一个，好测试功能。这里是找到子物体里最大的网格渲染器添加boxcollider，最好用于静态物体的添加
    [MenuItem("Tools/Collider/自动添加碰撞器(给所有子物体添加)", false, 100)]
    /// <summary>
    /// 自动添加碰撞器(给子物体添加，如建筑)
    /// </summary>
    public static void BindBoxColliderForWhole2()
    {//添加box碰撞器
        Debug.ClearDeveloperConsole();
        Object[] objs = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
        List<string> prefabPath = new List<string>();
        foreach (Object o in objs)
        {
            //Debug.Log(Application.dataPath.Replace("Assets", "")+AssetDatabase.GetAssetPath(o));
            //E:/ UnityProject / BorderExpansion / borderExpansionProj / Assets / Area730 / Stylized city / city.prefab
            FileInfo fi = new FileInfo(Application.dataPath.Replace("Assets", "") + AssetDatabase.GetAssetPath(o));
            //Debug.Log(fi.Name.Substring(fi.Name.LastIndexOf('.') + 1));
            if (fi.Name.Substring(fi.Name.LastIndexOf('.') + 1) == "prefab")
            {
                //prefabPath.Add(AssetDatabase.GetAssetPath(o));
                //Debug.Log(AssetDatabase.GetAssetPath(o));
                //Assets / Area730 / Stylized city / city.prefab
                //根对象
                GameObject srcClip = AssetDatabase.LoadAssetAtPath(AssetDatabase.GetAssetPath(o), typeof(GameObject)) as GameObject;
                for (int i = 0; i < srcClip.transform.childCount; i++)
                {
                    GameObject sub = srcClip.transform.GetChild(i).gameObject;
                    Debug.Log(sub.name);
                    Vector3 maxsize = Vector3.zero;
                    GameObject toAddColliderObj = null;
                    for (int j = 0; j < sub.transform.childCount; j++)
                    {
                        GameObject temp = sub.transform.GetChild(j).gameObject;
                        if (temp.GetComponent<BoxCollider>() != null)
                        {
                            continue;
                        }
                        Renderer smr = temp.GetComponentInChildren<Renderer>();
                        if (smr == null)
                        {
                            Debug.LogError(temp.ToString() + "没有MeshRenderer");
                            continue;
                        }
                        temp.AddComponent<BoxCollider>();
                    }
                    if (toAddColliderObj != null)
                    {
                        toAddColliderObj.gameObject.AddComponent<BoxCollider>();
                    }
                    else
                    {//没有child，如果自己本身有render则直接在自己身上加
                        if (sub.GetComponent<Renderer>() != null)
                        {
                            sub.gameObject.AddComponent<BoxCollider>();
                        }
                    }
                }
            }
        }
    }

    //模型大小由MeshRenderer决定，找到模型里面包含MeshRenderer的对象  给它加上网格碰撞器,这个碰撞不精确
    [MenuItem("Tools/Collider/自动添加碰撞器(给最上级的根对象添加，如角色模型)",false)]
	/// <summary>
	/// 自动添加碰撞器(给最上级的根对象添加，如角色模型)
	/// </summary>
    public static void BindBoxColliderForRole(GameObject obj=null)
    {//添加box碰撞器
		Object[] objs = Selection.GetFiltered (typeof(Object), SelectionMode.DeepAssets);
		foreach (Object o in objs) {
			BindBoxColliderForRole_Obj (o);
		}
    }

	/// <summary>
	/// 单个prefab添加碰撞器(角色考虑换成添加capsuleCollider)
	/// </summary>
	/// <param name="o">O.</param>
	public static void BindBoxColliderForRole_Obj(Object o,bool addBoxCollider=true,bool addCapsuleCollider=false){
		FileInfo fi = new FileInfo(Application.dataPath.Replace("Assets", "") + AssetDatabase.GetAssetPath(o));
		if (fi.Name.Substring(fi.Name.LastIndexOf('.') + 1) == "prefab")
		{
			GameObject srcClip = AssetDatabase.LoadAssetAtPath(AssetDatabase.GetAssetPath(o), typeof(GameObject)) as GameObject;
			if (srcClip.GetComponent<BoxCollider>() != null)
			{
				//已经有的就销毁...实际没删掉
				//GameObject.Destroy(srcClip.GetComponent<BoxCollider>());
				return;
			}
			//查找是否有网格渲染器
			Renderer smr = srcClip.GetComponentInChildren<Renderer>();
			if (smr == null) {
				Debug.LogError(srcClip.ToString() + "没有MeshRenderer");
				return;
			}
            //因为角色模型的网格一般比较大，这里缩小下 不用那么精确
            if (addCapsuleCollider)
            {
                CapsuleCollider cc = smr.gameObject.AddComponent<CapsuleCollider>();
                cc.radius = cc.radius * 0.8f;
                cc.height *= 0.5f;
            }
            else {
                BoxCollider bc = smr.gameObject.AddComponent<BoxCollider>();
                //bc.bounds = new Bounds(Vector3.zero, bc.bounds.size / 2);
                bc.size = new Vector3(bc.size.x / 2, bc.size.y / 2, bc.size.z * 5 / 6);//z的处理为了让collider更贴合模型高度
            }
        }
	}
}
